package cn.edu.swu.user;

import cn.edu.swu.database.DBTool;
import cn.edu.swu.database.resultsetVisitor;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class userRepo extends DBTool {
    private static userRepo instance=new userRepo();

    public static userRepo getInstance() {
        return instance;
    }
    public boolean addUser(USER newUser) throws SQLException {
        String insertTemplate ="insert into user(name,password) values('%s','%s')";
        String sql =String.format(insertTemplate,newUser.getUserName(),newUser.getUserPassword());
        System.out.println(sql);
        return this.execute(sql);
    }

    public List<USER> findUser(String name,String password) throws SQLException {
        String template="select * from user where name = '%s' and password = '%s'";
        String sql=String.format(template,name,password);
        return userRepo.instance.queryUser(sql);
    }

    public List<USER> queryUser(String sql) throws SQLException {
        final List<USER> users=new ArrayList<>();
        this.query(sql, new resultsetVisitor() {
            @Override
            //匿名类
            public void visit(ResultSet resultSet) {
                USER user=new USER();
                try{
                    user.setUserName(resultSet.getString("name"));
                    user.setUserPassword(resultSet.getString("password"));
                    users.add(user);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        return users;
    }


}
